package org.ko.core.logic.auth.impl;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import org.ko.core.dao.auth.UserDao;
import org.ko.core.dao.support.Updater;
import org.ko.core.domain.auth.User;
import org.ko.core.logic.auth.UserSvc;
import org.ko.core.websupport.page.Page;
import org.ko.core.websupport.security.encoder.Md5PwdEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

@Service
@Transactional
public class UserSvcImpl implements UserSvc {

	@Autowired
	private UserDao dao;
	
	
	/**
	 * 保存用户,编码为当前用户数加1格式化为0000四位
	 * 
	 * on 2014-9-17
	 * 增加了重名的判断，user name 不能重复
	 */
	public User addDo(User bean) {
		User oldUser = getByName(bean.getName());
		Assert.isNull(oldUser, "用户名"+bean.getName()+"已经存在，不能重复添加");

		Md5PwdEncoder encoder = new Md5PwdEncoder();
		//密码使用MD5加密
		bean.setPassword(encoder.encodePassword(bean.getPassword()));
		
		bean.setCreateDate(new Date());
		bean.setModifyDate(new Date());
		
		int cc =  dao.countByProperty() + 1;
		DecimalFormat df = new DecimalFormat("0000");
		bean.setUserNo(df.format(cc));
		dao.save(bean);
		
		return bean;
	}
	
	/**
	 * 批量删除指定id实例
	 */
	public void delete(Long[] ids) {
		dao.delete(ids);
	}


	public User editDo(User bean) {
		bean.setModifyDate(new Date());
		
		Updater<User> updater = new Updater<User>(bean);
		updater
		.exclude("password")
		.exclude("createDate")
		.exclude("USERNO");
		
		User ret = dao.updateByUpdater(updater);
		return ret;
	}


	@Override
	public Page findPage(Page p,String searchText) {
		return dao.findPage(p.getPageNo(), p.getPageSize(),searchText);
	}

	public User get(Long id) {
		return dao.get(id);
	}

	@Override
	public Page findForSelect(Page p, String keyword) {
		List<User> list = dao.findForSelect(p.getTotalCount(), p.getPageSize(), keyword);
		p.setList(list);
		
		return p;
	}

	/**
	 * 根据用户名获取用户
	 */
	@Override
	public User getByName(String name) {
		User user = dao.findUniqueByProperty("name", name);
		return user;
	}
}